﻿using System;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Xml;
using NAnt.Core;
using NAnt.Core.Attributes;

namespace RemoteWorker.NantTask
{
    [TaskName("check_worker")]
    [CallbackBehavior(IncludeExceptionDetailInFaults = true)]
    public class CheckWorkerTask : Task, INantTask
    {
        protected override void InitializeTask(XmlNode taskNode)
        {
            base.InitializeTask(taskNode);

            _server = new ServerConnection(this);
        }

        [TaskAttribute("workerName")]
        public string WorkerName { get; set; }

        [TaskAttribute("timeOutSec")]
        public int TimeOutSec { get; set; }

        protected override void ExecuteTask()
        {
            DateTime startTime = DateTime.Now;
            TimeSpan timeOutSpan = TimeSpan.FromSeconds(TimeOutSec);
            
            Log(Level.Info, string.Format("Waiting for {0}", WorkerName));
            
            while (true)
            {
                if (_server.CheckWorker(WorkerName))
                    break;
                
                if (timeOutSpan> TimeSpan.Zero && DateTime.Now - startTime >= timeOutSpan)
//              if (DateTime.Now - startTime >= timeOutSpan)
                {
                    Log(Level.Error, "Timeout");
                    throw new BuildException("Timeout");
                }
                
                Thread.Sleep(10);
            }
        }

        public void Log(string message)
        {
            lock (_lock)
            {
                _log.AppendLine(message);
            }
        }

        public void Complete(int exitCode)
        {
            Log(string.Format("exit code: {0}", exitCode));
            _done = true;
        }

        private ServerConnection _server;
        private bool _done;
        private StringBuilder _log;
        private object _lock = new object();
    }
}